package com.yq.homework.day30;

import java.io.*;
import java.lang.reflect.Field;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 3307235355@qq.com
 * @description
 * @since 2022/06/30 19:25
 * <p>
 * 多线程实现方式三:使用Callable的方式去实现之前的多线程文件复制,
 * 要求返回值为新文件的地址,
 * 接收该地址
 * 并且保存到一个文件里面
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CopyFile copyFile = new CopyFile(new File("a.txt"),new File("copy_a.txt"));
        FutureTask<String> fileFutureTask = new FutureTask<>(copyFile);
        Thread thread = new Thread(fileFutureTask);
        thread.start();
        String s = fileFutureTask.get();

        System.out.println("复制的文件的路径："+s);


    //保存到文件当中
        try ( FileWriter out =new FileWriter("load.txt");){
            out.write(s);
            System.out.println("文件路径保存成功！！！！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class CopyFile implements Callable<String> {
    File oldFile;
    File newFile;

    public CopyFile(File oldFile, File newFile) {
        this.oldFile = oldFile;
        this.newFile = newFile;
    }

    @Override
    public String call() throws Exception {

        // 复制文件操作
        try(FileInputStream in = new FileInputStream(oldFile);
            FileOutputStream out = new FileOutputStream(newFile)) {
            // System.out.println(newFile.getName());
            // 边读边写
            int readCount;
            byte[] bytes = new byte[1024];
            // 用来做累加的
            double temp = 0;
            long length = oldFile.length();
            while ((readCount = in.read(bytes)) != -1) {
                // write
                out.write(bytes);
                temp += readCount;
                double persent = temp / length * 100;
                System.out.println(oldFile + "复制了:"+String.format("%.2f",persent)+"%");
            }
            System.out.println(oldFile + "复制完成!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFile.getAbsolutePath();
    }


}